<?php

class Social_Api_Social
{

	/**
	 * @return array
	 */
	function getServices()
	{
		$cacheKey = 'social:getServices';

		if (FALSE == ($data = Nuo_Cache::instance()-> read($cacheKey)))
		{
			$table = Nuo::getTable('social/service');

			$select = $table -> select() -> where('is_enabled=1') -> order('sort_order');

			$rows = $table -> fetchAll($select);

			$data = array();

			foreach ($rows as $row)
			{
				$data[] = $row;
			}

			Nuo_Cache::instance()-> write($cacheKey, $data);
		}
		return $data;
	}

	/**
	 * add connect from none-user
	 * @param   $serviceId
	 * @param   array  $data {name, photo, uid, token, email, extra, link}
	 * @return  object
	 */
	function addConnect($serviceId, $data)
	{

		if (!isset($data['uid']) || empty($data['uid']))
		{
			throw new Exception('UID param is required!');
		}

		/**
		 * if is user
		 */
		$table = Nuo::getTable('social/connect');

		$userId = Nuo::getUserId();

		$select = $table -> select() -> where('user_id=?', $userId) -> where('service_id=?', $serviceId);

		$item = $table -> fetchRow($select);

		if (!$item)
		{
			$item = $table -> fetchNew();
			$item -> service_id = $serviceId;
			$item -> user_id = $userId;
		}

		$item -> uid = isset($data['uid']) ? $data['uid'] : '';

		$item -> name = isset($data['name']) ? $data['name'] : '';

		$item -> photo = isset($data['photo']) ? $data['photo'] : '';

		$item -> token = isset($data['token']) ? $data['token'] : '';

		$item -> email = isset($data['email']) ? $data['email'] : '';

		$item -> link = isset($data['link']) ? $data['link'] : '';

		$item -> login_at = time();

		$item -> save();
	}

}
